package com.veo.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("charset=UTF-8");
        int width=100;
        int height=50;
        //1.创建对象，在内存中图片（验证码图片对象）
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //2.美化图片
        //2.1填充背景颜色
        Graphics g=image.getGraphics();
        g.setColor(Color.gray);
        g.fillRect(0,0,width,height);
        //2.2画边框
        g.setColor(Color.black);
        g.drawRect(0,0,width-1,height-1);
        //2.3写验证码
        g.setColor(Color.orange);
        g.setFont(new Font("黑体",Font.BOLD,24));
        String code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvexyz0123456789";
        //生成角标
        Random ran=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=1;i<=4;i++){
            int index=ran.nextInt(code.length());//获取角标
            char ch=code.charAt(index);//获取字符
            sb.append(ch);
            g.drawString(ch+"",width/5*i,height/2);//写字符
        }
        //获取验证码值存入回话中
        String checkCode_session = sb.toString();
        req.getSession().setAttribute("checkCode_session",checkCode_session);
        //图片在页面显示
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
}
